/*
 * @Description:审批流程列表
 * @Author: LCL
 * @Date: 2021-11-23
 * @LastEditors: LCL
 * @LastEditTime: 2021-11-30
 * @FilePath: /beff/src/pages/ApprovalList/index.tsx
 */

import { Avatar, Card, Col, Divider, List, message, Row, Skeleton, Spin } from 'antd';
import InfiniteScroll from 'react-infinite-scroll-component';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import styles from './index.less';
import { getTypeCount, queryList } from './service';

const listObj = {
  ap: '我的申请',
  cp: '我的抄送',
  pt: '我的已办',
  td: '我的待办',
  draft: '我的草稿',
  turn: '我的转办',
};
const wfState = {
  active: '审批中',
  completed: '已完成',
  cancel: '已撤回',
  rejected: '已驳回',
};

interface ITypeCount {
  apCount: number;
  cpCount: number;
  dfCount: number;
  ptCount: number;
  tdCount: number;
  turnCount: number;
}

const ApprovalList = () => {
  const [listType, setListType] = useState('ap');
  const [typeData, setTypeData] = useState<ITypeCount>({
    apCount: 0,
    cpCount: 0,
    dfCount: 0,
    ptCount: 0,
    tdCount: 0,
    turnCount: 0,
  });
  const [listData, setListData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [pn, setPn] = useState(0);
  const [countSize, setCountSize] = useState(0);
  const ps = 10;
  const { initialState } = useModel('@@initialState');
  // const [listData, setListData] = useState<any[]>([]);
  // const handleClick = (type) => {
  //   setListType(type);
  // };

  // const {
  //   run: postRun,
  //   data: data,
  //   loading,
  //   ...others
  //   // mutate,
  // } = useRequest((type = 'ap', pageSize = '10', pageNum = '0') => {
  //   return queryList(
  //     {
  //       applicant: null,
  //       end: null,
  //       serialNum: null,
  //       start: null,
  //       title: null,
  //     },
  //     type,
  //     pageNum,
  //     pageSize,
  //   );
  // });

  const queryListFn = async (type: string, pageNum: number, pageSize: number) => {
    if (loading) {
      return;
    }
    setLoading(true);
    try {
      const res = await queryList(
        {
          applicant: null,
          end: null,
          serialNum: null,
          start: null,
          title: null,
        },
        type,
        pageNum,
        pageSize,
      );
      if (res.errorCode === '0') {
        let list = [...listData];
        if (type !== listType) {
          list = [];
          setCountSize(res.countSize);
        }
        setLoading(false);
        setPn(res.pageNumber + 1);
        setListData([...list, ...res.data]);
      } else {
        message.error(res.errorMsg || '请求失败');
        setLoading(false);
      }
    } catch (_) {
      message.error('服务请求失败');
      setLoading(false);
    }
  };

  const Info: React.FC<{
    title: React.ReactNode;
    type: string;
    value: React.ReactNode;
    bordered?: boolean;
  }> = ({ title, value, type, bordered }) => (
    <div
      className={classNames(styles.headerInfo, { [styles.chooseItem]: listType === type })}
      onClick={() => {
        if (loading) {
          return;
        }
        if (type !== listType) {
          setListData([]);
          queryListFn(type, 0, ps);
          setListType(type);
        }
      }}
    >
      <span>{title}</span>
      <p>{value}</p>
      {bordered && <em />}
    </div>
  );
  useEffect(() => {
    const userId = initialState?.userInfo?.userId;
    const fn = async () => {
      setLoading(true);
      try {
        const res = await getTypeCount(userId);
        if (res.errorCode === '0') {
          setTypeData(res.data);
        }
        const result = await queryList(
          {
            applicant: null,
            end: null,
            serialNum: null,
            start: null,
            title: null,
          },
          'ap',
          0,
          10,
        );
        if (res.errorCode === '0') {
          setListData([...result.data]);
          setCountSize(result.countSize);
          setPn(result.pageNumber + 1);
          setLoading(false);
        } else {
          message.error(res.errorMsg || '请求失败');
          setLoading(false);
        }
      } catch (_) {
        message.error('服务请求失败');
        setLoading(false);
      }
    };
    fn();
  }, [initialState?.userInfo?.userId]);

  return (
    <div className={styles.standardList}>
      <Card bordered={false}>
        <Row>
          <Col sm={4} xs={24}>
            <Info title="我的申请" type="ap" value={typeData.apCount} bordered />
          </Col>
          <Col sm={4} xs={24}>
            <Info title="我的待办" type="td" value={typeData.tdCount} bordered />
          </Col>
          <Col sm={4} xs={24}>
            <Info title="我的已办" type="pt" value={typeData.ptCount} bordered />
          </Col>
          <Col sm={4} xs={24}>
            <Info title="我的转办" type="turn" value={typeData.turnCount} bordered />
          </Col>
          <Col sm={4} xs={24}>
            <Info title="我的抄送" type="cp" value={typeData.cpCount} bordered />
          </Col>
          <Col sm={4} xs={24}>
            <Info title="我的草稿" type="draft" value={typeData.dfCount} />
          </Col>
        </Row>
      </Card>
      <Card
        className={styles.listCard}
        bordered={false}
        title={listObj[listType]}
        style={{ marginTop: 24 }}
        bodyStyle={{ padding: '0 32px 40px 32px' }}
        // extra={extraContent}
      >
        <Spin spinning={loading}>
          <div
            id="scrollableDiv"
            style={{
              height: 640,
              overflow: 'auto',
              padding: '0 16px',
              border: '1px solid rgba(140, 140, 140, 0.35)',
            }}
          >
            <InfiniteScroll
              dataLength={listData.length}
              next={() => {
                queryListFn(listType, pn, ps);
              }}
              hasMore={listData.length < countSize}
              loader={null}
              endMessage={!loading && <Divider plain>已经到底了 🤐</Divider>}
              scrollableTarget="scrollableDiv"
            >
              <List
                dataSource={listData}
                size="large"
                rowKey="id"
                renderItem={(item: any) => (
                  <List.Item
                    className={styles.list}
                    actions={[
                      <a
                        key="edit"
                        onClick={(e) => {
                          e.preventDefault();
                          const type = item?.businessKey?.split('.')[0] || '';
                          // history.push(`approval/detail?sn=${item.serialNum}&type=${type}`);
                          window.open(
                            `approval/detail?sn=${item.serialNum}&type=${type}&taskId=${
                              item.taskId
                            }&title=${item.title?.split('的')[1]}`,
                          );
                        }}
                      >
                        查看详情
                      </a>,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar src={item.imageUrl} shape="square" size="large" />}
                      title={
                        listType === 'ap'
                          ? `审批人：${item.assignee || '无'}`
                          : `申请人：${item.startZhName}`
                      }
                      description={`标题：${item.title?.split('的')[1]}`}
                    />
                    {/* <ListContent data={item} /> */}
                    <div className={styles.listContent}>
                      <div className={styles.listContentItem}>
                        <span>任务到达时间</span>
                        <p>{item.startTime}</p>
                      </div>
                      <div className={styles.listContentItem}>
                        <span>流水号</span>
                        <p>{item.serialNum}</p>
                      </div>
                      <div className={styles.listContentItem}>
                        <span>审批节点</span>
                        <p>{item.nodeName || '无'}</p>
                      </div>
                      <div className={styles.listContentItem}>
                        <span>审批状态</span>
                        <p>{wfState[item.wfState]}</p>
                      </div>
                    </div>
                  </List.Item>
                )}
              />
            </InfiniteScroll>
          </div>
        </Spin>
      </Card>
    </div>
  );
};

export default ApprovalList;
